from email.header import Header
import smtplib
from email.mime.text import MIMEText


class Sender:
    def __init__(self, smtp_server, smtp_port, from_mail, to_mail, password, cc_mail = None):
        self.smtp_server = smtp_server
        self.smtp_port = smtp_port
        self.from_mail = from_mail
        self.to_mail = to_mail
        self.password = password
        self.cc_mail = cc_mail

    def send_mail(self, msg):
        smtp = None
        try:
            smtp = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port)
            smtp.login(self.from_mail, self.password)
            smtp.sendmail(self.from_mail, self.to_mail, msg.as_string())
        except smtplib.SMTPRecipientsRefused:
            print("Recipient refused")
        except smtplib.SMTPAuthenticationError:
            print("Auth error")
        except smtplib.SMTPSenderRefused:
            print("Sender refused")
        else:
            print('success')
        finally:
            smtp.quit()


class MsgGenerator:
    def __init__(self, subject, from_mail_name, from_mail, to_mail):
        self.subject = subject
        self.from_mail_name = from_mail_name
        self.from_mail = from_mail
        self.to_mail = to_mail

    def plain_msg(self, data):
        msg = MIMEText(data, 'plain', 'utf-8')
        msg['Subject'] = Header(self.subject, 'utf-8')
        msg['From'] = Header(self.from_mail_name + ' <' + self.from_mail + '>', 'utf-8')
        msg['To'] = Header(','.join(self.to_mail), 'utf-8')
        return msg